package com.example.authclient.controller;

import com.taocares.security.core.SecurityHelper;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Description goes here
 *
 * @author Ankang
 * @date 2018/12/19
 */
@Controller
@RequestMapping("/")
public class PageController {

    @Autowired
    private ObjectProvider<OAuth2RestOperations> restOperationsProvider;

    @RequestMapping("/")
    public String hello(HttpSession session) {
        Authentication authentication = SecurityHelper.getUserAuthentication();
        session.setAttribute("authentication", authentication);
        session.setAttribute("username", SecurityHelper.getCurrentUsername());
        session.setAttribute("loginType", SecurityHelper.getLoginType());
        session.setAttribute("details", SecurityHelper.getCurrentUserDetails());
        session.setAttribute("sessionId", SecurityHelper.getSessionId());
        session.setAttribute("remoteAddress", SecurityHelper.getRemoteAddress());
        return "index";
    }

    @RequestMapping("/secured")
    public String secured(HttpSession session) {
        session.setAttribute("remote-result", "Local Request!!!");
        return "index";
    }

    @RequestMapping("/local")
    public String local(HttpSession session) {
        session.setAttribute("remote-result", "Local Request!!!");
        return "index";
    }

    @RequestMapping("/remote")
    public String remote(HttpSession session, HttpServletRequest request) {
        OAuth2RestOperations restTemplate = restOperationsProvider.getIfAvailable();
        if (restTemplate != null) {
            ResponseEntity<String> result = restTemplate.getForEntity("http://localhost:8080/api/test", String.class);
            session.setAttribute("remote-result", result);
        } else {
            session.setAttribute("remote-result", "No RestTemplate Available!");
        }
        return "index";
    }

    @RequestMapping("/page/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/unauthorized")
    public String unauthorized() {
        return "unauthorized";
    }
}
